package com.logic.landseaserver.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.logic.landseaserver.common.enums.BillTypeEnum;
import com.logic.landseaserver.common.util.ConstantChar;
import com.logic.system.persistence.read.CodeReadMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.logic.common.security.SecurityUtils;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.config.FileConfiguration;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.exception.ResultCodes.BillManageResultCode;
import com.logic.landseaserver.common.util.DateUtil;
import com.logic.landseaserver.persistence.read.BillReadMapper;
import com.logic.landseaserver.service.IBillRecord;
import com.logic.landseaserver.ws.dto.BillRecordDTO;

@Service
public class BillRecordServiceImpl implements IBillRecord, EnvironmentAware
{
    
    private static final String ENV_FILE_PATH = "logic.file.path.";
    
    private static final String EXCEL_PATH = "excelPath";
    
    private static final String REMOTE_PATH = "remote";
    
    private static RelaxedPropertyResolver propertyResolver;
    
    private static final Logger logger = LoggerFactory.getLogger(BillRecordServiceImpl.class);
    
    @Autowired
    private BillReadMapper billReadMapper;
    
    @Autowired
    private FileConfiguration fileConfiguration;

    @Autowired
    private CodeReadMapper codeReadMapper;
    
    @Override
    public List<BillRecordDTO> getBillRecordList(QueryUtil queryUtil)
    {
        List<BillRecordDTO> dto = billReadMapper.getMostBillInfo(queryUtil);
        //付租方式，账单类型，城市公司，付款方式，
       /* List<String> parCodes = new ArrayList<>();
        parCodes.add("_PAMO");//付租方式
        parCodes.add("_BT");//账单类型
        parCodes.add("AREA");//城市公司
        parCodes.add("_PATY");//付款方式
        parCodes.add("_CTBI");//账单项
        List<Map<String, Object>> codes = codeReadMapper.queryByParCodes(parCodes);
        System.out.println("start"+new Date());
        for(BillRecordDTO recordDTO:dto){
            recordDTO.setPaymentModeZH(getCodeName(codes,recordDTO.getPaymentMode()));
            recordDTO.setBillTypeName(getCodeName(codes,recordDTO.getBillType()));
            recordDTO.setAreaCodeZH(getCodeName(codes,recordDTO.getAreaCode()));
            if(recordDTO.getPayType()!=null){
                recordDTO.setPayTypeZH(getCodeName(codes,recordDTO.getPayType()));
            }
        }
        System.out.println("end"+new Date());*/
        return dto;
    }

    private String getCodeName(List<Map<String, Object>> codes,String code){
       for(int i=0;i<codes.size();i++){
           String codeName = (String)codes.get(i).get(code);
           if(StringUtils.isNotEmpty(codeName)){
                return codeName;
           }
       }
        return "";
    }
    
    @Override
    public String downloadBillRecordExcel(QueryUtil queryUtil)
        throws Exception
    {
        StringBuffer url = propertyResolver.getProperty(REMOTE_PATH, StringBuffer.class, null);
        StringBuffer excelpath = propertyResolver.getProperty(EXCEL_PATH, StringBuffer.class, null);
        
        InputStream ins = null;
        Workbook wb = null;
        try
        {
            ins = BillRecordServiceImpl.class.getClassLoader().getResourceAsStream("收款日记账.xlsx");
            wb = WorkbookFactory.create(ins);
        }
        catch (Exception e)
        {
            logger.error("exportPropertyList error.", e);
            throw LandseaException.createException(BillManageResultCode.E00250001, e);
        }
        finally
        {
            try
            {
                ins.close();
            }
            catch (IOException e)
            {
                logger.error("exportPropertyList error.", e);
            }
        }
        
        List<BillRecordDTO> list = billReadMapper.getMostBillInfo(queryUtil);
        if (list != null && list.size() > 0)
        {
            Sheet sheet = wb.getSheet("收款日记账");
            // 生成一个样式
            CellStyle style = wb.createCellStyle();
            // 设置这些样式
            style.setAlignment(CellStyle.ALIGN_CENTER);
            // 生成一个字体
            Font font = wb.createFont();
            font.setFontHeightInPoints((short)14);
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            // 把字体应用到当前的样式
            style.setFont(font);
            
            Row row;
            DecimalFormat df = new DecimalFormat("0.00");
            int startRow = 2;
            for (int i = 0; i < list.size(); i ++)
            {
                
                BillRecordDTO object = list.get(i);
                row = sheet.createRow(startRow);
                row.createCell(0).setCellValue(i + 1);
                
                row.createCell(1).setCellValue(object.getAreaCodeZH() == null ? "" : object.getAreaCodeZH()); // 公司名 即
                                                                                                              // 地区
                row.createCell(2).setCellValue(object.getPrjName() == null ? "" : object.getPrjName()); // 门店 即 项目名
                
                // 账单编号
                row.createCell(3).setCellValue(object.getBillNo() == null ? "" : object.getBillNo());
                // 账单月
                row.createCell(4).setCellValue(object.getBillMonth() == null ? "" : object.getBillMonth());
                // 账单名
                row.createCell(5).setCellValue(object.getBillName() == null ? "" : object.getBillName());
                
                // 收款日期
                row.createCell(6).setCellValue(DateUtil.convertDateTime(object.getPayTime()));
                
                row.createCell(7)
                    .setCellValue(object.getBillDetailTypeZH() == null ? "" : object.getBillDetailTypeZH()); // 收款内容 即
                row.createCell(8).setCellValue(object.getPaymentModeZH() == null ? "" : object.getPaymentModeZH()); // 收款方式 即
                                                                                                            // 支付方式
                if (object.getMoney() == null){
                    row.createCell(9).setCellValue(""); // 收款金额
                } else{
                    row.createCell(9).setCellValue(df.format(object.getMoney())); // 收款金额
                }
                row.createCell(10).setCellValue(object.getTransactionNo() == null ? "" : object.getTransactionNo()); // 收款单号
                row.createCell(11).setCellValue(object.getOperatorName() == null ? "" : object.getOperatorName()); // 经办人
                                                                                                                  // 即bill表createBy
                row.createCell(12).setCellValue(object.getContractNo() == null ? "" : object.getContractNo()); // 合同编号
                row.createCell(13).setCellValue(object.getHouseNum() == null ? "" : object.getHouseNum()); // 房间编号 即房间号
                row.createCell(14)
                    .setCellValue(object.getCertificatesName() == null ? "" : object.getCertificatesName()); // 客户姓名 即
                                                                                                             // 合同上姓名
                row.createCell(15).setCellValue(object.getPayTypeZH() == null ? "" : object.getPayTypeZH()); // 付款方式
                if (object.getCertificateInDate() == null){
                    row.createCell(16).setCellValue(""); // 起始日
                }else{
                    String time = DateUtil.convertDateTime(object.getCertificateInDate());
                    row.createCell(16).setCellValue(time); // 起始日
                }
                if (object.getCertificateOutDate() == null){
                    row.createCell(17).setCellValue(""); // 终止日
                }else{
                    String time = DateUtil.convertDateTime(object.getCertificateOutDate());
                    row.createCell(17).setCellValue(time); // 终止日
                }
                
                Double rentprice = object.getRentPrice();
                Double depositprice = object.getDepositPrice();
                Double fee = object.getPropertyFee();
                if (rentprice == null) {
                    row.createCell(18).setCellValue(""); // 住宿费
                } else{
                    row.createCell(18).setCellValue(df.format(rentprice));
                }
                
                if (depositprice == null){
                    row.createCell(19).setCellValue(""); // 押金
                }else {
                    row.createCell(19).setCellValue(df.format(depositprice));
                }
                
                if (fee == null) {
                    row.createCell(20).setCellValue(""); // 服务费
                }else {
                    row.createCell(20).setCellValue(df.format(fee));
                }
                
                if (object.getBillTypeBeginDate() == null){
                    row.createCell(21).setCellValue(""); // 起始日
                }else{
                    String time = DateUtil.convertDateTime(object.getBillTypeBeginDate());
                    row.createCell(21).setCellValue(time); // 起始日
                }
                
                if (object.getBillTypeEndDate() == null){
                    row.createCell(22).setCellValue(""); // 终止日
                }else{
                    String time = DateUtil.convertDateTime(object.getBillTypeEndDate());
                    row.createCell(22).setCellValue(time); // 终止日
                }
                
                row.createCell(23).setCellValue(object.getRemark() == null ? "" : object.getRemark()); // 备注
                startRow = startRow + 1;
            }
            /*
             * //总计 row = sheet.createRow(startRow); row.createCell(0).setCellValue("总计");
             * row.createCell(7).setCellFormula("SUM(H3:F"+startRow+")");
             */
        }
        
        OutputStream fos = null;
        try
        {
            Integer userId = SecurityUtils.getCurrentLogin().getUserId();
            String filepath = fileConfiguration.getLocal() + "/" + excelpath;
            // String filepath = "C://work";
            File file = new File(filepath);
            // 如果文件夹不存在则创建
            if (!file.exists() && !file.isDirectory())
            {
                file.mkdir();
            }
            // 删除userId开头的excel
            String[] files = file.list(new FilenameFilter()
            {
                @Override
                public boolean accept(File dir, String name)
                {
                    return name.endsWith(".xlsx");
                }
            });
            for (String f : files)
            {
                if (f.startsWith(userId + "-"))
                {
                    new File(filepath + "/" + f).delete();
                }
            }
            
            Date nowTime = new Date(System.currentTimeMillis());
            SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String time = sdFormatter.format(nowTime);
            
            String fileName = "收款日记账单_" + time +".xlsx";
            fos = new FileOutputStream(filepath + "/" + fileName);
            wb.write(fos);
            
            StringBuffer returnUrl = new StringBuffer();
            returnUrl.append(url);
            returnUrl.append("/");
            returnUrl.append(excelpath);
            returnUrl.append("/");
            returnUrl.append(fileName);
            return returnUrl.toString();
            
        }
        catch (Exception e)
        {
            logger.error("exportPropertyList error.", e);
            return null;
        }
        finally
        {
            try
            {
                fos.flush();
                fos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    public void setEnvironment(Environment environment)
    {
        propertyResolver = new RelaxedPropertyResolver(environment, ENV_FILE_PATH);
    }
}
